/*
This file is part of vlc-remote.

vlc-remote is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

vlc-remote is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with vlc-remote.  If not, see <http://www.gnu.org/licenses/>.
*/
Qt.include("remoteControl.js");
Qt.include("remoteStatus.js");

var VLC_MAX_VOLUME = 1024;

function VlcRemote(ipAddress) {
    this._init(ipAddress);
}

VlcRemote.prototype = {
    __proto__: RemoteControl.prototype,

    _statusQueued: false,

    _ipAddress: "",

    _connected: false,

    _init: function(ipAddress) {
            this._ipAddress = ipAddress;
        },

    _getRootUrl: function() {
        return "http://" + this._ipAddress;
     },

    _getStatusUrl: function() {
        return this._getRootUrl() + "/requests/status.xml";
     },

    _makeSimpleActionRequest: function(action, update_status) {
        var here = this;
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
                ; // NO OP
            } else if (xhr.readyState == XMLHttpRequest.DONE) {
                if (200 == xhr.status && update_status) {
                    here._processStatus(xhr.responseXML);
                }
            }
        }
        var data = "?command=" + action;
        //console.debug(this._getStatusUrl() + "?command=" + action);
        xhr.open("GET", this._getStatusUrl() + data);
        xhr.send();
    },

    _processStatus: function(data) {
        var rs = new RemoteStatus();
        var root = data.documentElement;
        for (var i = 0; i < root.childNodes.length; ++i) {
            var child = root.childNodes[i];
            var nt = child.nodeType;
            var name = child.nodeName;
            var val = child.nodeValue;
            var nodes = child.childNodes;
            if (3 != nt && nodes && nodes[0]) {
                val = nodes[0].nodeValue;
                switch (name) {
                case "volume":
                    rs.volume = (100 * val / VLC_MAX_VOLUME).toFixed(0) ;
                    break;
                case "length":
                    rs.duration = (val * 1000).toFixed(0);
                    break;
                case "time":
                    rs.position = (val * 1000).toFixed(0);
                    break;
                case "state":
                    switch (val) {
                    case "playing":
                        rs.state = RemoteState.PLAYING;
                        break;
                    case "paused":
                        rs.state = RemoteState.PAUSED;
                        break;
                    case "stop":
                        rs.state = RemoteState.STOPPED;
                        break;
                    default:
                        rs.state = RemoteState.UNKNOWN;
                        break;
                    }
                    break;
                case "position": // percentage track played
                    rs.percentagePlayed = (1 * val).toFixed(0);
                    break;
                case "fullscreen":
                    //rs.position = val;
                    break;
                case "random":
                    rs.shuffle = ((1 * val).toFixed(0) == 0) ? ShuffleMode.FORWARD : ShuffleMode.SHUFFLE;
                    break;
                case "loop":
                    rs.repeat = ((1 * val).toFixed(0) == 0) ? RepeatMode.NONE : RepeatMode.ALL;
                    break;
                case "repeat":
                    //rs.repeat = ((1 * val).toFixed(0) == 0) ? RepeatMode.NONE : RepeatMode.ALL;
                    break;
                case "information":
                    var info = nodes;
                    for (var j = 0; j < info.length; ++j) {
                        nt = info[j].nodeType;
                        name = info[j].nodeName;
                        val = info[j].nodeValue;
                        var infoNodes = info[j].childNodes;
                        switch (name) {
                        case "category":
                            break;
                        case "meta-information":
                            var meta = infoNodes;
                            for (var k = 0; k < meta.length; ++k) {
                                nt = meta[k].nodeType;
                                name = meta[k].nodeName;
                                val = meta[k].nodeValue;
                                switch (name) {
                                case "title":
                                    rs.title = meta[k].childNodes[0].nodeValue;
                                    break;
                                case "artist":
                                    rs.artist = meta[k].childNodes[0].nodeValue;
                                    break;
                                case "album":
                                    rs.album = meta[k].childNodes[0].nodeValue;
                                    break;
                                case "genre":
                                    rs.genre = meta[k].childNodes[0].nodeValue;
                                    break;
                                }
                            }
                            break;
                        }
                    }
                    break;
                case "stats":
                    break;
                }
            }
        }
        rs.uid = rs.title + rs.artist + rs.duration;
        rs.id = rs.uid;
        this._statusQueued = false;
        this._updateStatus(rs)
    },

    getIpAddress: function() {
        return this._ipAddress;
    },

    ping: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == XMLHttpRequest.HEADERS_RECEIVED) {
                ; // what to do
            } else if (xhr.readyState == XMLHttpRequest.DONE) {
                if (200 == xhr.status) {
                    ; // emit ping success
                    console.log("Success!");
                }
                else {
                    ; // emit ping failed
                    console.log("Failure!");
                }
            }
        }
        xhr.open("GET", this._getStatusUrl());
        xhr.send();
    },

    requestStatus: function() {
        if (!this._statusQueued) {
            this._statusQueued = true;
            this._makeSimpleActionRequest("", true);
        }
    },

    requestTrackNext: function() {
        this._makeSimpleActionRequest("pl_next", true);
    },

    requestTrackById: function(trackId) {
        this._makeSimpleActionRequest("pl_play&id=" + trackId, false);
    },

    requestTrackByPath: function(path) {
        //console.debug(path);
        this._makeSimpleActionRequest("in_play&input=" + path.replace(/\\/g, '\\\\'), false);
    },

    requestTrackPrevious: function() {
        this._makeSimpleActionRequest("pl_previous", true);
    },

    requestStartPlayback: function() {
        this._makeSimpleActionRequest("pl_play", true);
    },

    requestResumePlayback: function() {
        this._makeSimpleActionRequest("pl_pause", true);
    },

    requestStopPlayback: function() {
        this._makeSimpleActionRequest("pl_stop", true);
    },

    requestPausePlayback: function() {
        this._makeSimpleActionRequest("pl_pause", true);
    },

    requestSetVolume: function(volume) {
        var vol = (volume * VLC_MAX_VOLUME).toFixed(0);
        this._makeSimpleActionRequest("volume&val=" + vol, false);
    },

    requestSeekToPercentage: function(percentage) {
        this._makeSimpleActionRequest("seek&val=" + percentage.toFixed(0) + "%25", false);
    },

    requestToggleFullscreen: function() {
        this._makeSimpleActionRequest("fullscreen", false);
    },

    requestToggleShuffle: function() {
        this._makeSimpleActionRequest("pl_random", true);
    },

    requestToggleLoop: function() {
        this._makeSimpleActionRequest("pl_loop", true);
    },

    requestQueueByPath: function(path) {
        this._makeSimpleActionRequest("in_enqueue&input=" + path.replace(/\\/g, '\\\\'), false);
    },

    requestClearPlaylist: function() {
        this._makeSimpleActionRequest("pl_empty", false);
    },

    requestDeleteFromPlaylist: function(id) {
        this._makeSimpleActionRequest("pl_delete&id=" + id, false);
    }

}
